class Sys::NavigationsController < ApplicationController
  def index
    render json: tree_to_json(Navigation.root)
  end

  private

  def tree_to_json(root)
    result = []
    json = {}
    root.descendants.each do |node|
      if node.depth == 1
        result << json unless json.empty?
        json = node_to_json(node)
        json[:children] = []
      else
        json[:children] << node_to_json(node)
      end
    end
    result << json unless json.empty?
    result
  end

  def node_to_json(node)
    {
        :id => node.id,
        :text => node.text,
        :leaf => node.leaf,
        :expanded => node.expanded,
        :icon_cls => node.icon_cls,
        :glyph => node.glyph,
        :model => node.model,
        :url => node.url,
        :module => node.module
    }
  end
end